﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using GMAC.ReportingSystem.Business.Entities;
using System.Data;
using Entities = GMAC.ReportingSystem.Business.Entities;
using Components = GMAC.ReportingSystem.Business.Components;
using FrameworkManapro.Utilities;

namespace GMAC.ReportingSystem.Paginas
{
    public partial class Agents : System.Web.UI.Page
    {
        #region Page Events

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated || Session["User"] == null)
            {
                System.Web.Security.FormsAuthentication.RedirectToLoginPage();
                return;
            }
            if (IsPostBack) return;
            Initialize();
            ValidateSecurity();
        }

        #endregion

        #region Button Events

        
        protected void btnSave_Click(object sender, ImageClickEventArgs e)
        {
            btnSave.Visible = false;
            var frc = new Components.AgentComponent();
            try
            {
                var Agent = ReadAgent();
                if (hfAgentID.Value.Trim() != string.Empty)
                {
                    Agent.ID = int.Parse(hfAgentID.Value);
                    var oldAgent = frc.GetDetails(Agent.ID);
                    frc.Edit(Agent);
                    var audit = new FrameworkManapro.Audit.Audit<Entities.Agent>
                    {
                        EntityKey = Agent.ID.ToString(),
                        EventDate = DateTime.Now,
                        EventType = FrameworkManapro.Audit.AuditEvent.Update,
                        OldObject = oldAgent,
                        NewObject = Agent,
                        UserId = ((Entities.User)Session["User"]).UserID
                    };
                    var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<Entities.Agent>(audit);
                    auditDAC.InsertAudit();
                    wucMessage.ShowMessage(UserControls.MessageType.Success, "The Agent was successfully saved.", null);
                    popupExtenderMessage.Show();
                    this.PagingControl.TotalRecords = Search();
                    Search();
                    ClearFields();
                }
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Save Agent", "btnSave_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The Agent couldn't be saved.", null);
                popupExtenderMessage.Show();
            }
        }
        protected void btnCancel_Click(object sender, ImageClickEventArgs e)
        {
            btnSave.Visible = false;
            ClearFields();
        }
        protected void btnModify_Click(object sender, ImageClickEventArgs e)
        {
            if (grvAgents != null)
            {
                if (grvAgents.SelectedDataKey != null)
                {
                    try
                    {
                        var AgentId = (int)this.grvAgents.SelectedDataKey.Value;
                        var frc = new Components.AgentComponent();
                        var Agent = frc.GetDetails(AgentId);
                        hfAgentID.Value = AgentId.ToString();

                        txtUser.Text = Agent.UserName;
                        txtFirstName.Text = Agent.FirstName;
                        txtLastName.Text = Agent.LastName;
                        ddlType.SelectedValue = ((int)Agent.TypeAgent).ToString();
                        if (!string.IsNullOrEmpty(Agent.ManagementGroup.ToString()))
                        {
                            ddlManagementGroup.SelectedValue = ((int)Agent.ManagementGroup).ToString();
                        }
                        
                        ddlTurn.SelectedValue = ((int)Agent.Turn).ToString();
                        optOptions.SelectedValue = Agent.Status.ToString();
                        btnSave.Visible = true;
                    }
                    catch (Exception ex)
                    {
                        FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Modify Agent", "btnModify_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                        wucMessage.ShowMessage(UserControls.MessageType.Error, "An error has occurred changing the Agent.", ex.ToString());
                        popupExtenderMessage.Show();
                    }
                }
                else
                {
                    wucMessage.ShowMessage(UserControls.MessageType.Information, "A agent must be selected.", null);
                    popupExtenderMessage.Show();
                }
            }
        }

        protected void btnConfirm_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                var frc = new Components.AgentComponent();
                if (grvAgents.SelectedDataKey != null)
                {
                    var AgentId = (int)this.grvAgents.SelectedDataKey.Value;
                    var Agent = new Entities.Agent { ID = AgentId };
                    var oldAgent = frc.GetDetails(Agent.ID);
                    frc.Delete(Agent);
                    var audit = new FrameworkManapro.Audit.Audit<Entities.Agent>
                    {
                        EntityKey = Agent.ID.ToString(),
                        EventDate = DateTime.Now,
                        EventType = FrameworkManapro.Audit.AuditEvent.Delete,
                        OldObject = oldAgent,
                        UserId = ((Entities.User)Session["User"]).UserID
                    };
                    var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<Entities.Agent>(audit);
                    auditDAC.InsertAudit();
                    this.PagingControl.TotalRecords = Search();
                    Search();
                    wucMessage.ShowMessage(UserControls.MessageType.Success, "The Agent was successfully deleted.", null);
                    popupExtenderMessage.Show();
                }
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Delete Agent", "btnConfirm_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The Agent couldn't be deleted.", ex.ToString());
                popupExtenderMessage.Show();
            }

        }
        protected void imgBuscarReg_Click(object sender, ImageClickEventArgs e)
        {
            this.PagingControl.TotalRecords = Search();
            Search();
            if (this.PagingControl.TotalRecords == 0)
            {
                PagingControl.Visible = false;
            }
            else
            {
                PagingControl.Visible = true;
            }
            ClearFields();
            
        }

        #endregion

        #region Other Events

        protected void grvAgents_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes["OnClick"] = ClientScript.GetPostBackEventReference(grvAgents, "Select$" + e.Row.RowIndex);
                if (bool.Parse((e.Row.FindControl("hfStatus") as HiddenField).Value) == true)
                {
                    e.Row.Cells[6].Text = "Active";
                }
                else
                {
                    e.Row.Cells[6].Text = "Inactive";
                }
                Entities.GeneralEnumTypes.TypeAgent TypeAgent = (Entities.GeneralEnumTypes.TypeAgent)Enum.Parse(typeof(Entities.GeneralEnumTypes.TypeAgent), (e.Row.FindControl("hdTypeId") as HiddenField).Value);
                e.Row.Cells[3].Text = TypeAgent.ToString().Replace('_', ' ');

                if (!string.IsNullOrEmpty((e.Row.FindControl("hdManagementGroup") as HiddenField).Value))
                {
                    int ManagementGroup = int.Parse((e.Row.FindControl("hdManagementGroup") as HiddenField).Value);
                    if (ManagementGroup==2)
                        e.Row.Cells[4].Text = hdMoraTemprana.Value;
                    else
                        e.Row.Cells[4].Text = hdOver.Value;
                }
                

                Entities.GeneralEnumTypes.Turn Turn = (Entities.GeneralEnumTypes.Turn)Enum.Parse(typeof(Entities.GeneralEnumTypes.Turn), (e.Row.FindControl("hdTurn") as HiddenField).Value);
                e.Row.Cells[5].Text = Turn.ToString().Replace('_', ' ');
                
            }
        }

        #endregion

        #region Private Methods

        private void ClearFields()
        {
            txtUser.Text = string.Empty;
            txtFirstName.Text = string.Empty;
            txtLastName.Text = string.Empty;
            ddlType.SelectedValue = string.Empty;
            ddlManagementGroup.SelectedValue = string.Empty;
            ddlTurn.SelectedValue = string.Empty;
            optOptions.SelectedValue = "True";

            txtUserSearch.Text = string.Empty;
            txtFirstNameSearch.Text = string.Empty;
            txtLastNameSearch.Text = string.Empty;
            ddlTypeSearch.SelectedValue = string.Empty;
            ddlManagementGroupSearch.SelectedValue = string.Empty;
            ddlTurnSearch.SelectedValue = string.Empty;

            hfAgentID.Value = string.Empty;

        }
        private void Initialize()
        {
            try
            {
                foreach (int i in Enum.GetValues(typeof(GeneralEnumTypes.TypeAgent)))
                {
                    this.ddlType.Items.Add(new ListItem(Enum.GetName(typeof(GeneralEnumTypes.TypeAgent), i).ToString().Replace('_', ' '), i.ToString()));
                    this.ddlTypeSearch.Items.Add(new ListItem(Enum.GetName(typeof(GeneralEnumTypes.TypeAgent), i).ToString().Replace('_', ' '), i.ToString()));
                }
                this.ddlType.Items.Insert(0, new ListItem("Select...", String.Empty));
                this.ddlTypeSearch.Items.Insert(0, new ListItem("Select...", String.Empty));

                foreach (int i in Enum.GetValues(typeof(GeneralEnumTypes.Turn)))
                {
                    this.ddlTurn.Items.Add(new ListItem(Enum.GetName(typeof(GeneralEnumTypes.Turn), i).ToString().Replace('_', ' '), i.ToString()));
                    this.ddlTurnSearch.Items.Add(new ListItem(Enum.GetName(typeof(GeneralEnumTypes.Turn), i).ToString().Replace('_', ' '), i.ToString()));
                }
                this.ddlTurn.Items.Insert(0, new ListItem("Select...", String.Empty));
                this.ddlTurnSearch.Items.Insert(0, new ListItem("Select...", String.Empty));

                var gpc = new Components.GeneralParameterComponent();
                DataTable dt = gpc.GetConfigurationValues(17);
                string parametro_general_etiqueta_mora_temprana = dt.Rows[0].ItemArray[3].ToString().Trim();
                dt = gpc.GetConfigurationValues(18);
                string parametro_general_etiqueta_over = dt.Rows[0].ItemArray[3].ToString().Trim();

                hdMoraTemprana.Value = parametro_general_etiqueta_mora_temprana;
                hdOver.Value = parametro_general_etiqueta_over;

                this.ddlManagementGroup.Items.Add(new ListItem(parametro_general_etiqueta_mora_temprana,"2"));
                this.ddlManagementGroup.Items.Add(new ListItem(parametro_general_etiqueta_over, "1"));
                this.ddlManagementGroup.Items.Insert(0, new ListItem("Select...", String.Empty));

                this.ddlManagementGroupSearch.Items.Add(new ListItem(parametro_general_etiqueta_mora_temprana, "2"));
                this.ddlManagementGroupSearch.Items.Add(new ListItem(parametro_general_etiqueta_over, "1"));
                this.ddlManagementGroupSearch.Items.Insert(0, new ListItem("Select...", String.Empty));

                optOptions.SelectedValue = "True";
                btnSave.Visible = false;
                wucMessageConfirm.ShowMessage(UserControls.MessageType.Information,
                                              "Are you sure you want to delete the selected agent", null);
                this.PagingControl.TotalRecords = Search();
                Search();
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Initialize page", "Initialize", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "An error occurred initializing the page.", ex.ToString());
                popupExtenderMessage.Show();
            }

        }
        private void ValidateSecurity()
        {
            var beEntities = ((User)Session["User"]).Role.Security.GetEntitySecurity("Agents");
            if (beEntities == null) return;
            if (!beEntities.CanRead)
            {
                grvAgents.Visible = false;
                btnModify.Visible = false;
                pnlSearch.Visible = false;
            }
            if (!beEntities.CanWrite)
            {
                btnSave.Visible = false;
            }
            if (!beEntities.CanInsert)
            {
                btnCancel.Visible = false;
                pnlEdit.Visible = false;
            }

        }
        private int Search()
        {
            try
            {
                var bc = new Components.AgentComponent();
                

                string UserName = txtUserSearch.Text;
                string FirstName = txtFirstNameSearch.Text;
                string LastName = txtLastNameSearch.Text;
                int? ManagementGroup = null;
                if (!string.IsNullOrEmpty(ddlManagementGroupSearch.SelectedValue))
                    ManagementGroup = Convert.ToInt32(ddlManagementGroupSearch.SelectedValue);
                int? Turn = null;
                if (!string.IsNullOrEmpty(ddlTurnSearch.SelectedValue))
                    Turn = Convert.ToInt32(ddlTurnSearch.SelectedValue);
                int? TypeAgent = null;
                if (!string.IsNullOrEmpty(ddlTypeSearch.SelectedValue))
                    TypeAgent = Convert.ToInt32(ddlTypeSearch.SelectedValue);

                FrameworkManapro.WebUI.PagingDetails paging = new FrameworkManapro.WebUI.PagingDetails();
                paging.PageNumber = this.PagingControl.PageNumber;
                paging.PageSize = this.PagingControl.PageSize;
                paging.SortBy = this.PagingControl.SortExpression;
                paging.SortDirection = this.PagingControl.SortDirection;



                Entities.AgentCollection Agentcollection = bc.Search(UserName, FirstName, LastName, ManagementGroup,Turn,TypeAgent, paging);

                grvAgents.DataSource = Agentcollection;
                grvAgents.DataBind();
                return Agentcollection.TotalResults;
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Search Agent", "void Search", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "An error has occurred during the search.", ex.ToString());
                popupExtenderMessage.Show();
                return 0;

            }
        }
        private Entities.Agent ReadAgent()
        {
            var Agent = new Entities.Agent
            {
                ID = int.Parse(hfAgentID.Value),
                UserName = txtUser.Text,
                FirstName = txtFirstName.Text,
                LastName = txtLastName.Text,
                TypeAgent = (Entities.GeneralEnumTypes.TypeAgent)Enum.Parse(typeof(Entities.GeneralEnumTypes.TypeAgent), ddlType.SelectedValue.ToString()),
                ManagementGroup = int.Parse(ddlManagementGroup.SelectedValue),
                Turn = (Entities.GeneralEnumTypes.Turn)Enum.Parse(typeof(Entities.GeneralEnumTypes.Turn), ddlType.SelectedValue.ToString()),
                Status = bool.Parse(optOptions.SelectedValue),
            };
            return Agent;
        }
        protected void pagingControl_PageChanged(object sender, EventArgs e)
        {
            Search();
        }
        #endregion

        
    }
}
